package cn.wolfcode.trip.api.socket; /**
 * @Class: WebSocketMessageService
 * @Description: 使用webscoket连接向用户发送信息
 * @author linhongxiang
 */

import cn.wolfcode.trip.base.domain.Chat;
import cn.wolfcode.trip.base.domain.ChatRecord;
import cn.wolfcode.trip.base.mapper.ChatMapper;
import cn.wolfcode.trip.base.mapper.ChatRecordMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("webSocketMessageService")
public class WSMessageService {
    private Logger logger = LoggerFactory.getLogger(WSMessageService.class);
    //声明websocket连接类
    private WebsocketDemo websocketDemo = new WebsocketDemo();

    @Autowired
    private ChatMapper chatMapper;

    @Autowired
    private ChatRecordMapper chatRecordMapper;

    /**
     * @Title: sendToAllTerminal
     * @Description: 调用websocket类给用户下的所有终端发送消息
     * @param @param userId 用户id
     * @param @param message 消息
     * @param @return 发送成功返回true，否则返回false
     */
    public Boolean sendToAllTerminal(ChatRecord chatRecord) {
        logger.debug("向用户{}的消息：{}", chatRecord.getReceiver().getId(), chatRecord.getContent());
        // 保存当前两个的关联用户
        Chat chat = new Chat();
        chat.setSender(chatRecord.getSender());
        chat.setReceiver(chatRecord.getReceiver());
        // 查询数据库中是否已经有此关联
        Chat theChat = chatMapper.queryBySenderIdAndReceiverId(chat);
        // 如果还没有这两个人的关联，插入chat表，新建关联
        if (theChat == null) {
            chatMapper.insert(chat);
            chatRecord.setChat(chat);
        } else {
            chatRecord.setChat(theChat);
        }
        // 把消息记录到数据库
        chatRecordMapper.insert(chatRecord);
        // 发送消息
        if (websocketDemo.sendMessageToUser(chatRecord.getReceiver().getId(), chatRecord.getContent())) {
            return true;
        } else {
            return false;
        }
    }
}